package com.klhappy.houyuan.fragement;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.klhappy.houyuan.R;
import com.klhappy.houyuan.bean.AddressBean.DeAddressBean;
import com.klhappy.houyuan.bean.AddressBean.DefaultAddress;
import com.klhappy.houyuan.bean.BaseJsonBean;
import com.klhappy.houyuan.bean.JiaYuanBean;
import com.klhappy.houyuan.bean.JiaYuanNuBean;
import com.klhappy.houyuan.constant.KeyConstant;
import com.klhappy.houyuan.dialog.NetWorkDialog;
import com.klhappy.houyuan.dialog.Photograph;
import com.klhappy.houyuan.interfaces.CallBackInterModle;
import com.klhappy.houyuan.activity.About_HouyuanActivity;
import com.klhappy.houyuan.activity.Add_AddressActivity;
import com.klhappy.houyuan.activity.ExtractMoneyActivity;
import com.klhappy.houyuan.activity.Family_MemberActivity;
import com.klhappy.houyuan.activity.Food_StampActivity;
import com.klhappy.houyuan.activity.NameReviseActivity;
import com.klhappy.houyuan.modle.JiaYuanModle;
import com.klhappy.houyuan.utils.ConfigManager;
import com.klhappy.houyuan.utils.JsonCode;
import com.klhappy.houyuan.utils.headshot.CropImageActivity;
import com.klhappy.houyuan.utils.headshot.HeadShotUtil;
import com.klhappy.houyuan.utils.okhttp.BaseBeanCallback;
import com.klhappy.houyuan.utils.okhttp.ImgBean;
import com.klhappy.houyuan.utils.okhttp.OkHttpUtils;
import com.klhappy.houyuan.view.AbsFragment;
import com.klhappy.houyuan.constant.UrlConstant;
import com.klhappy.houyuan.view.CircleImageView;
import com.klhappy.houyuan.view.banner.DisplayUtil;
import com.klhappy.houyuan.view.pullzoomview.PullToZoomScrollViewExForMe;
import com.squareup.okhttp.Request;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class Jiayuan_Fragment extends AbsFragment implements CallBackInterModle {
    private TextView family_num;
    private TextView loction_nu;
    private TextView stamps_nu;
    private TextView feat_nu;
    private TextView tv_username;
    private TextView tv_recommondedcode;

    private ImageView me_zoom_view;
    private CircleImageView iv_icon;

    private LinearLayout my_self;
    private RelativeLayout rl_family_member;
    private RelativeLayout rl_receiving_address;
    private RelativeLayout rl_home_stamps;
    private RelativeLayout rl_my_feat;
    private RelativeLayout rl_about;

    private JiaYuanModle modle;
    private boolean flag = false;
    private JiaYuanNuBean nuBean;
    private NetWorkDialog dialog;

    private File file_sdcard;
    private File mHeadShotDir;
    private File mHeaderImg;
    private File mBackImg;
    private static String localTempImageFileName = "";
    private Photograph photograph;
    private String header;
    private String back;
    private boolean flagX = true;
    private String isKey;//表示存储的key

    private DeAddressBean de;
    private DefaultAddress deaddress;

    private View parentView, contentView, zoomView;
    private RelativeLayout rootContainer;
    private FrameLayout headerContainer;
    private PullToZoomScrollViewExForMe pull_view;

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mConfigManage = getAppEnv().getConfigManager();
        parentView = inflater.inflate(R.layout.home, container, false);
        pull_view = (PullToZoomScrollViewExForMe) parentView.findViewById(R.id.pull_view);
        pull_view.setHeaderViewSize(DisplayUtil.getWindowWidth(getActivity()), DisplayUtil.getWindowHeight(getActivity()) / 3);

        intView();
        modle = new JiaYuanModle(getActivity());
        modle.setCallBackInterModle(this);
        dialog = new NetWorkDialog(getActivity());
        return parentView;
    }


    private void intView() {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.item_header, null);
        rootContainer = (RelativeLayout) view.findViewById(R.id.me_root_container);
        headerContainer = (FrameLayout) view.findViewById(R.id.me_header_container);
        contentView = view.findViewById(R.id.me_content_container);
        headerContainer.setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, DisplayUtil.getWindowHeight(getActivity()) / 3));//设置初始图片高度为屏幕高度的三分之一
        zoomView = view.findViewById(R.id.me_zoom_view);
        pull_view.setLayout(rootContainer, headerContainer, contentView, zoomView);
        pull_view.setZoomEnabled(true);
        family_num = (TextView) view.findViewById(R.id.family_num);
        loction_nu = (TextView) view.findViewById(R.id.loction_nu);
        stamps_nu = (TextView) view.findViewById(R.id.stamps_nu);
        feat_nu = (TextView) view.findViewById(R.id.feat_nu);
        tv_username = (TextView) view.findViewById(R.id.tv_username);
        tv_recommondedcode = (TextView) view.findViewById(R.id.tv_recommondedcode);
        me_zoom_view = (ImageView) view.findViewById(R.id.me_zoom_view);
        iv_icon = (CircleImageView) view.findViewById(R.id.iv_icon);

        initImageFileCache();

        //背景图
        me_zoom_view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                flagX = true;
                isKey = KeyConstant.BACK;
                back = KeyConstant.BACK + ".png";
                mConfigManage.set(KeyConstant.BACK ,back);
                setDialogX(KeyConstant.BACK);
            }
        });
        //头像图
        iv_icon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                flagX = false;
                isKey = KeyConstant.HEADER;
                header = KeyConstant.HEADER + ".png";
                mConfigManage.set(KeyConstant.HEADER ,header);
                setDialogX(KeyConstant.HEADER);
            }
        });
        my_self = (LinearLayout) view.findViewById(R.id.my_self);
        my_self.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), NameReviseActivity.class));
            }
        });
        //家庭成员
        rl_family_member = (RelativeLayout) view.findViewById(R.id.rl_family_member);
        rl_family_member.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), Family_MemberActivity.class));
            }
        });
        //收货地址
        rl_receiving_address = (RelativeLayout) view.findViewById(R.id.rl_receiving_address);
        rl_receiving_address.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), Add_AddressActivity.class));
            }
        });
        //后院粮票
        rl_home_stamps = (RelativeLayout) view.findViewById(R.id.rl_home_stamps);
        rl_home_stamps.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity() ,Food_StampActivity.class);
                intent.putExtra("flag" ,false);
                startActivity(intent);
            }
        });
        //我的业绩
        rl_my_feat = (RelativeLayout) view.findViewById(R.id.rl_my_feat);
        rl_my_feat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), ExtractMoneyActivity.class));
            }
        });
        //关于后院
        rl_about = (RelativeLayout) view.findViewById(R.id.rl_about);
        rl_about.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), About_HouyuanActivity.class));
            }
        });
    }

    private void setView() {
        tv_username.setText(mConfigManage.get(KeyConstant.myname, ""));
        if (mConfigManage.get(KeyConstant.inv_code, "") == null && mConfigManage.get(KeyConstant.inv_code, "").equals("")) {
            tv_recommondedcode.setText("推荐码:" + "无");
        } else {
            tv_recommondedcode.setText("推荐码:" + mConfigManage.get(KeyConstant.inv_code, ""));
        }

        Picasso.with(getActivity())
                .load(UrlConstant.BASE_URL + mConfigManage.get(KeyConstant.headerimg, ""))
                .placeholder(R.drawable.head_new_img)
                .error(R.drawable.head_new_img)
                .into(iv_icon);

        Picasso.with(getActivity())
                .load(UrlConstant.BASE_URL + mConfigManage.get(KeyConstant.default_bg, ""))
                .placeholder(R.drawable.head_new_img)
                .error(R.drawable.head_new_img)
                .into(me_zoom_view);
    }

    @Override
    public void onResume() {
        super.onResume();
        modle.getJiaYuan(getActivity());
        modle.getDeAddress();
        setView();
    }

    @Override
    public void CallBackFromModle(String url, BaseJsonBean o) {
        if (url.equals(UrlConstant.HOMEINFOR_URL)) {
            if (o.getCode() == 200) {
                Gson gson = new Gson();
                Log.e("this" ,"===:" + gson.toJson(o));
                JiaYuanBean bean = JsonCode.getClass(o.getEntity(), JiaYuanBean.class);
                nuBean = JsonCode.getClass(bean.getRecords(), JiaYuanNuBean.class);
                try {
                    setText();
                } catch (Exception e) {

                }
                flag = true;
            } else {
                dialog.netWork(o.getMsg());
                dialog.show();
            }
        }else if (url.equals(UrlConstant.DEADDRESS_URL)){
            if (o.getCode() == 200){
                de = JsonCode.getClass(o.getEntity(), DeAddressBean.class);
                deaddress = JsonCode.getClass(de.getDefaultAddress(), DefaultAddress.class);
                mConfigManage.remove(KeyConstant.ADDRESS);
                mConfigManage.set(KeyConstant.ADDRESS, deaddress.getId() + "");
            }
        }
    }

    private void setText() {
        if (null != nuBean.getUserNo() && !"".equals(nuBean.getUserNo())){
            family_num.setText(nuBean.getUserNo() + "位");
        }
        if (null != nuBean.getAddressNo() && !"".equals(nuBean.getAddressNo())){
            loction_nu.setText(nuBean.getAddressNo() + "个");
        }
        if (null != nuBean.getFoodsNo() && !"".equals(nuBean.getFoodsNo())){
            stamps_nu.setText(nuBean.getFoodsNo() + "张");
        }
        if (null != nuBean.getMoneys()){
            feat_nu.setText(nuBean.getMoneys() + "元");
        }else {
            feat_nu.setText("0元");
        }

        tv_username.setText(mConfigManage.get(KeyConstant.myname, ""));
        if (mConfigManage.get(KeyConstant.inv_code, "") == null && mConfigManage.get(KeyConstant.inv_code, "").equals("")) {
            tv_recommondedcode.setText("推荐码:" + "无");
        } else {
            tv_recommondedcode.setText("推荐码:" + mConfigManage.get(KeyConstant.inv_code, ""));
        }
    }

    //创建文件夹
    private void initImageFileCache() {
        file_sdcard = Environment.getExternalStorageDirectory();
        mHeadShotDir = new File(file_sdcard, KeyConstant.APP_DIR
                + File.separator + KeyConstant.IMAGE_DIR + File.separator
                + KeyConstant.HEAD_SHOT);
        if (!mHeadShotDir.exists()) {
            mHeadShotDir.mkdirs();
        }
        try {
            initData();
        }catch (Exception e){

        }
    }

    //获取本地图片加载并获取file路径
    private void initData() {
        mHeadShotDir = new File(file_sdcard, KeyConstant.APP_DIR
                + File.separator + KeyConstant.IMAGE_DIR + File.separator
                + KeyConstant.HEAD_SHOT);
        if (!mHeadShotDir.exists()) {
            mHeadShotDir.mkdirs();
        }
        String header = mConfigManage.get(KeyConstant.HEADER, "");
        mHeaderImg = new File(mHeadShotDir, header);
        if (mHeaderImg.exists()) {
            Bitmap headShot = HeadShotUtil.getHeadShot(header);
            if (headShot != null) {
                iv_icon.setImageBitmap(headShot);
            } else {
                Log.d("mao", "initData  图片加载失败");
            }
        }
        String back = mConfigManage.get(KeyConstant.BACK ,"");
        mBackImg = new File(mHeadShotDir, back);
        if (mBackImg.exists()) {
            Bitmap headShot = HeadShotUtil.getHeadShot(back);
            if (headShot != null) {
                me_zoom_view.setImageBitmap(headShot);
            } else {
                Log.d("mao", "initData  图片加载失败");
            }
        }
    }
    private void setDialogX(final String key){
        photograph = new Photograph(getActivity()) {
            @Override
            public void doGoToImg() {
                super.doGoToImg();
                this.dimiss();
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_PICK);
                intent.setType("image/*");
                startActivityForResult(intent, KeyConstant.FLAG_CHOOSE_IMG);
            }

            @Override
            public void doGoToPhone() {
                super.doGoToPhone();
                this.dimiss();
                String status = Environment.getExternalStorageState();
                if (status.equals(Environment.MEDIA_MOUNTED)) {
                    try {
                        localTempImageFileName = mConfigManage.get(key ,"");
                        if (!mHeadShotDir.exists()) {
                            mHeadShotDir.mkdirs();
                        }
                        Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                        File f = new File(mHeadShotDir, localTempImageFileName);
                        Uri u = Uri.fromFile(f);
                        intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, u);
                        startActivityForResult(intent, KeyConstant.FLAG_CHOOSE_PHONE);
                    } catch (ActivityNotFoundException e) {
                        Toast.makeText(getActivity(),
                                "相机打开失败", Toast.LENGTH_SHORT).show();
                    }

                } else {
                    Toast.makeText(getActivity(), "手机未安装SD卡",
                            Toast.LENGTH_SHORT).show();
                }
            }
        };

        photograph.show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == KeyConstant.FLAG_CHOOSE_IMG) {
            if (data != null) {
                Uri uri = data.getData();
                if (!TextUtils.isEmpty(uri.getAuthority())) {
                    Cursor cursor = getActivity().getContentResolver().query(uri,
                            new String[]{MediaStore.Images.Media.DATA},
                            null, null, null);
                    if (null == cursor) {
                        showToastx("图片没找到!");
                        return;
                    }
                    cursor.moveToFirst();
                    String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                    cursor.close();
                    Intent intent = new Intent(getActivity(), CropImageActivity.class);
                    intent.putExtra("path", path);
                    intent.putExtra("key" ,isKey);
                    startActivityForResult(intent, KeyConstant.FLAG_MODIFY_FINISH);
                } else {
                    Intent intent = new Intent(getActivity(), CropImageActivity.class);
                    intent.putExtra("path", uri.getPath());
                    intent.putExtra("key" ,isKey);
                    startActivityForResult(intent,
                            KeyConstant.FLAG_MODIFY_FINISH);
                }
            }
        } if (requestCode == KeyConstant.FLAG_CHOOSE_PHONE) {
            File f = new File(mHeadShotDir, localTempImageFileName);
            Intent intent = new Intent(getActivity(), CropImageActivity.class);
            intent.putExtra("path", f.getAbsolutePath());
            intent.putExtra("key" ,isKey);
            startActivityForResult(intent, KeyConstant.FLAG_MODIFY_FINISH);
        } if (requestCode == KeyConstant.FLAG_MODIFY_FINISH) {
            if (flagX){
                if (data != null) {
                    String imgName = mConfigManage.get(KeyConstant.BACK, "");
                    Bitmap headShot = HeadShotUtil.getHeadShot(imgName);
                    if (headShot != null) {
                        me_zoom_view.setImageBitmap(headShot);
                    }
                }
                String url = UrlConstant.ACCOUNT_URL;

                Map<String, String> params = new HashMap<>();
                params.put("action", "4");

                Map<String, String> headers = new HashMap<>();
                headers.put("cookie", mConfigManage.get(KeyConstant.session, ""));


                String header = mConfigManage.get(KeyConstant.BACK, "");
                mBackImg = new File(mHeadShotDir, header);

                OkHttpUtils.post()
                        .addFile("back_file", mConfigManage.get(KeyConstant.BACK, ""), mBackImg)
                        .url(url)
                        .params(params)
                        .headers(headers)
                        .build()
                        .execute(new BaseBeanCallback() {
                            @Override
                            public void onError(Request request, Exception e) {
                                Log.e("this", e.toString());
                                closeDialog();
                            }

                            @Override
                            public void onResponse(ImgBean imgBean) {
                                Gson gson = new Gson();
                                Log.e("this", gson.toJson(imgBean));
                                showToastx(imgBean.msg);
                                closeDialog();
                            }
                        });
            }else {
                if (data != null) {
                    String imgName = mConfigManage.get(KeyConstant.HEADER, "");
                    Bitmap headShot = HeadShotUtil.getHeadShot(imgName);
                    if (headShot != null) {
                        iv_icon.setImageBitmap(headShot);
                    }
                }

                String url = UrlConstant.ACCOUNT_URL;

                Map<String, String> params = new HashMap<>();
                params.put("action", "3");

                Map<String, String> headers = new HashMap<>();
                headers.put("cookie", mConfigManage.get(KeyConstant.session, ""));

                String header = mConfigManage.get(KeyConstant.HEADER, "");
                mHeaderImg = new File(mHeadShotDir, header);

                OkHttpUtils.post()
                        .addFile("header_file", mConfigManage.get(KeyConstant.HEADER, ""), mHeaderImg)
                        .url(url)
                        .params(params)
                        .headers(headers)
                        .build()
                        .execute(new BaseBeanCallback() {
                            @Override
                            public void onError(Request request, Exception e) {
                                Log.e("this", e.toString());
                                closeDialog();
                            }

                            @Override
                            public void onResponse(ImgBean imgBean) {
                                Gson gson = new Gson();
                                Log.e("this", gson.toJson(imgBean));
                                showToastx(imgBean.msg);
                                closeDialog();
                            }
                        });
            }

        }
    }
}
